package com.kch.web.controller.system;

import com.kch.common.annotation.Log;
import com.kch.common.core.controller.BaseController;
import com.kch.common.core.domain.AjaxResult;
import com.kch.common.enums.BusinessType;
import com.kch.common.json.JSON;
import com.kch.framework.util.ShiroUtils;
import com.kch.system.domain.OtherConfig;
import com.kch.system.service.IOtherConfigService;
import com.kch.system.vo.AboutVO;
import com.kch.web.config.CloumnProperties;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

@Controller
@RequestMapping("/system/about")
@Api(tags = "关于我们")
public class AboutController extends BaseController {


    private String prefix = "system/about";

    @Autowired
    private IOtherConfigService otherConfigService;
    @Autowired
    private CloumnProperties cloumnProperties;

    @RequiresPermissions("system:about:view")
    @GetMapping()
    public String index(ModelMap mmap) throws Exception {
        OtherConfig otherConfig = otherConfigService.selectByCloCode(cloumnProperties.getAbout(), null);
        AboutVO aboutVO = new AboutVO();
        if (!ObjectUtils.isEmpty(otherConfig)) {
            aboutVO = JSON.unmarshal(otherConfig.getContent(), AboutVO.class);
            aboutVO.setId(otherConfig.getId());
        }
        mmap.put("about", aboutVO);
        return prefix + "/about";
    }

    @Log(title = "关于我们", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated AboutVO aboutVO) throws Exception {
        OtherConfig otherConfig = otherConfigService.selectByCloCode(cloumnProperties.getAbout(), aboutVO.getId());
        if (ObjectUtils.isEmpty(otherConfig)) {
            OtherConfig config = new OtherConfig();
            config.setCreateTime(new Date());
            config.setCreateBy(ShiroUtils.getLoginName());
            config.setCloumnCode(cloumnProperties.getAbout());
            config.setContent(JSON.marshal(aboutVO));
            otherConfigService.insertOtherConfig(config);
        } else {
            otherConfig.setContent(JSON.marshal(aboutVO));
            otherConfig.setUpdateBy(ShiroUtils.getLoginName());
            otherConfig.setUpdateTime(new Date());
            otherConfigService.updateById(otherConfig);
        }
        return toAjax(true);
    }
}
